const gulp = require('gulp'),
      htmlmin = require('gulp-htmlmin'),
      sass = require('gulp-sass'),
      autoPrefixer = require('gulp-autoprefixer'),
      cleanCss = require('gulp-clean-css'),
      uglify = require('gulp-uglify'),
      babel = require('gulp-babel'),
      del = require('del'),
      con = require('gulp-connect')
      // { createProxyMiddleware } = require('http-proxy-middleware')
      

const paths = {
  html: {
    src: 'src/**/*.html',
    dest: 'dist'
  },
  css: {
    src: 'src/css/**/*.scss',
    dest: 'dist/css'
  },
  js: {
    src: 'src/js/**',
    dest: 'dist/js'
  },
  images: {
    src: 'src/images/**',
    dest: 'dist/images'
  },
  libs: {
    src: 'src/libs/**',
    dest: 'dist/libs'
  },
  ico: {
    src: 'src/favicon.ico',
    dest: 'dist'
  },
  api: {
    src: 'src/api/**',
    dest: 'dist/api'
  }
}

const delDist = () => {
  return del('dist')
}

const html = () => {
  return gulp.src(paths.html.src)
    .pipe(htmlmin({
      removeComments: true,//清除HTML注释
      collapseWhitespace: true,//压缩HTML
      collapseBooleanAttributes: true,//省略布尔属性的值 <input checked="true"/> ==> <input checked />
      removeEmptyAttributes: true,//删除所有空格作属性值 <input id="" /> ==> <input />
      removeScriptTypeAttributes: false,//删除<script>的type="text/javascript"
      removeStyleLinkTypeAttributes: true,//删除<style>和<link>的type="text/css"
      minifyJS: true,//压缩页面JS
      minifyCSS: true//压缩页面CSS 
  }))
    .pipe(gulp.dest(paths.html.dest))
    .pipe(con.reload())
}

const css = () => {
  return gulp.src(paths.css.src)
    .pipe(sass())
    .pipe(autoPrefixer())
    .pipe(cleanCss())
    .pipe(gulp.dest(paths.css.dest))
    .pipe(con.reload())
}

const js = () => {
  return gulp.src(paths.js.src)
  //  .pipe(babel({
  //   presets: ['@babel/env']
  //   }))
  //  .pipe(uglify())
   .pipe(gulp.dest(paths.js.dest))
   .pipe(con.reload())
}

const images = () => gulp.src(paths.images.src).pipe(gulp.dest(paths.images.dest))

const libs = () => gulp.src(paths.libs.src).pipe(gulp.dest(paths.libs.dest))

const ico = () => gulp.src(paths.ico.src).pipe(gulp.dest(paths.ico.dest))

const api = () => gulp.src(paths.api.src).pipe(gulp.dest(paths.api.dest))

const watch = () => {
  gulp.watch(paths.html.src, html)
  gulp.watch(paths.css.src, css)
  gulp.watch(paths.js.src, js)
}

const server = () => {
  con.server({
    root: 'dist',
    port: 8081,
    livereload: true
    // 代理跨域：把以/api开头的请求代理到拼多多的接口
    // middleware () {
    //   return [
    //     createProxyMiddleware('/pc', {
    //       target: 'https://app2.motie.com',
    //       changeOrigin: true
    //     })
    //   ]
    // }
  })
}


module.exports.default = gulp.series(delDist, gulp.parallel(html, css, js, images, libs, watch, server, ico, api))